<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm"  class="login-form" autocomplete="on" label-position="left">

      <div class="title-container">
        <span class="logo"></span>
      </div>
      <div class="info-container">
        <div class="left">
            <span class="pic"></span>
        </div>
        <div class="right">
          <div class="directform-container">
              <div class="title">龙南汽车管理系统</div>
             <el-form-item prop="username" style="margin-top:60px;">
              <span class="svg-container">
                <img src="../../assets/icon_user.png" width="25" height="25"> 
              </span>
              <el-input
                ref="username"
                v-model="loginForm.username"
                placeholder="输入手机号码"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>

            <el-tooltip v-model="capsTooltip" content="已开启大写" placement="right" manual>
              <el-form-item prop="password" v-show="loginType==1">
                <span class="svg-container">
                    <img src="../../assets/icon_password.png" width="22" height="25"> 
                </span>
                <el-input
                  :key="passwordType"
                  ref="password"
                  v-model="loginForm.password"
                  :type="passwordType"
                  placeholder="密 码"
                  name="password"
                  tabindex="2"
                  autocomplete="on"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  @keyup.enter.native="handleLogin"
                />
                <span class="show-pwd" @click="showPwd">
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </el-form-item>
            </el-tooltip>

            <el-form-item prop="verifycode"  v-show="loginType==2">
              <span class="svg-container">
                <img src="../../assets/icon_verifycode.png" width="22" height="25"> 
              </span>
              <el-input
                ref="verifycode"
                v-model="loginForm.verifycode"
                placeholder="输入验证码"
                name="verifycode"
                type="text"
                tabindex="2"
                autocomplete="off" style="width:240px;"
              />
              <el-button :loading="loading" :disabled="waiting" type="primary" style="width:120px;margin-left:10px;" @click="sendPhoneCode()">{{btnSendPhoneCodeText}}</el-button>
            </el-form-item>
            <!-- <div class="verifycode-desc"  v-show="loginType==2">
                若该手机号未注册，我们将自动为您注册
            </div> -->
            <div class="btns" style="text-align:center">
            <el-button :loading="loading" type="primary" style="width:180px;margin-bottom:30px;" @click.native.prevent="handleLogin">登   录</el-button>
            </div>
            <div class="typechange">
                <span @click="changeLoginType()">{{loginTypeText}}</span>
            </div>
          </div>
        </div>
      </div>
     
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import md5 from 'js-md5'
import {getPhoneCode} from '@/api/user'


export default {
  name: 'Login',
  components: {  },
  data() {
    return {
      loginType:1,
      loginTypeText:'验证码登录',
      waiting:false,
      waitingTime:60,
      waitingItv:0,
      btnSendPhoneCodeText:'发送验证码',
      loginForm: {
        username: '',
        password: '',
        verifycode:''
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      var that=this;
      if(!that.loginForm.username){
          that.$message({
            message: '请输入手机号码',
            type: 'warning'
          });
          return;
        }
      if(that.loginType==1){
        
        if(!that.loginForm.password){
          that.$message({
            message: '请输入密码',
            type: 'warning'
          });
          return;
        }
      }else{
        
        if(!that.loginForm.verifycode){
          that.$message({
            message: '请输入验证码',
            type: 'warning'
          });
          return;
        }
      }
      this.loading = true;
      if(that.loginType==1){
          
          var random = new Date().getTime().toString();
          var pwd = md5(
              this.loginForm.username +
              md5(this.loginForm.password)+
              random
          );
          const options = {
            phone: this.loginForm.username,
            pwd: pwd,
            random
          };
          this.$store.dispatch("user/adminLogin", options)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch((err) => {
              this.$message({
                message:err,
                type:'danger'
              })
              this.loading = false
            })
      }else{
        const options = {
            Phone: that.loginForm.username,
            PhoneCode: that.loginForm.verifycode,
            Type:3,
          };
          this.$store.dispatch("user/adminPhoneLogin", options)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.$message({
                message:err,
                type:'danger'
              })
              this.loading = false
            })
      }
        
    },
    sendPhoneCode(){
      var that=this;
      if(that.waiting){return;}
      if(!that.loginForm.username || /^[1]([3-9])[0-9]{9}$/.test(that.loginForm.username)==false){
        that.$message({
            message: '请填写正确的手机号码',
            type: 'warning'
          });
          return;
      }
      
      that.waiting=true;
      that.waitingTime=20;
      
      getPhoneCode({phone:that.loginForm.username}).then(res=>{
        if(res.data){
          that.$message({
            message: '验证码已发送，请注意查收手机短信',
            type: 'success'
          });
          that.waitingItv=setInterval(()=>{
             that.waitingTime=that.waitingTime-1;
             that.btnSendPhoneCodeText=that.waitingTime+'秒后可重发';
             if(that.waitingTime<1){
               that.waiting=false;
               that.btnSendPhoneCodeText='重新获取';
               clearInterval(that.waitingItv);
             }
          },1000)
        }
      }).catch(()=>{
        that.waiting=false;
      })

    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    changeLoginType(){
      this.loginType=(this.loginType==1?2:1);
      this.loginTypeText=(this.loginType==1?'验证码登录':'密码登录');
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background: url('../../assets/bg_loginpage.png') no-repeat;
  background-size:cover;

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #666;
      height: 47px;
      font-size:16px;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #666 !important;
      }
    }
  }

  .el-form-item {
    border-bottom: 1px solid #ccc;
    color: #454545;
  }
  .verifycode-desc{
    color:#C1C9CE;
    font-size:14px;
    margin-bottom:20px;
  }

  .typechange{
    color:#128BF1; text-align: center;font-size: 16px;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .login-form {
    position: relative;
    width: 1000px;
    height: 635px;
    padding:40px 70px; 
    box-sizing: border-box;
    border-radius: 4px;
    max-width: 100%;
    background: #ffffff;
    background: url(../../assets/bg_loginbox.png) no-repeat;
    background-size: cover;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 0px 0px;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .logo{
      //background: url(../../assets/logo.png) no-repeat;
      display: block;
      width:170px;
      height: 37.5px;
      background-size: contain;
    }
  }

  .info-container{
    display: flex;
    height: calc(100% - 47.5px);
    .left{ 
      width:50%;
      height: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      span.pic{
        display: block;
         width:400px;
         height: 290px;
         background: url(../../assets/pic_loginpage.png) no-repeat;
         background-size: contain;
      }
    }

    .right{
      width:50%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .directform-container{
         width:400px;
         height: 400px;


         .title{
           width:100%;
           height: 40px;
           line-height: 40px;
           color:#128BF1;
           font-size: 24px;
           text-align: center;
           font-weight: bold;
           margin-bottom: 30px;
         }
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
